package com.yejiali.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yejiali.backend.common.constants.SystemContants;
import com.yejiali.backend.common.httpcode.HttpCodeEnum;
import com.yejiali.backend.entity.User;
import com.yejiali.backend.entity.dto.RegisterDTO;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.RegisterService;
import com.yejiali.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author:yejiali
 * @Date:2025/5/11-05-11-16:48
 * @Decsription:com.yejiali.backend.service.impl
 * @Version:1.0
 */
@Service("registerService")
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;

    @Override
    public Response register(RegisterDTO user) {
        //已通过注解对user必要字段进行校验
        // 先判断用户名是否存在
        if (userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername())) != null) {
            return Response.error(HttpCodeEnum.USER_ALREADY_EXISTS.getCode(), "用户名已存在");
        }
        //判断头像是否为空
        if (user.getAvatar() == null || user.getAvatar().isEmpty()) {
            // 设置默认头像
            user.setAvatar(SystemContants.DEFAULT_AVATAR);
        }
        //密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //拷贝对象存入数据库
        User userInfo = BeanUtil.copyProperties(user, User.class);
        userService.save(userInfo);
        return Response.success("注册成功");
    }
}
